﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace CSharpSnake
{
    //生产者消费者模式，新建一个线程收集键盘输入 （避免阻塞主线程），外部可以消耗掉输入
    class Input
    {
        //线程锁
        private object lockObject = new object();
        //一段时间内获取到的键盘输入
        private List<ConsoleKey> inputKeys = new List<ConsoleKey>();

        //在构造方法中开启一个新的线程，用于获取键盘输入
        public Input()
        {
            Thread inputThread = new Thread(() =>
            {
                while(true)
                {
                    ConsoleKeyInfo keyInfo = Console.ReadKey();
                    ConsoleKey inputKey = keyInfo.Key;
                    lock (lockObject)
                    {
                        inputKeys.Add(inputKey);
                    }
                }

            });
            inputThread.Start();
        }

        //外部消耗掉最近一段时间的输入
        public List<ConsoleKey> ConsumeInput()
        {
            List<ConsoleKey> result = new List<ConsoleKey>();
            lock(lockObject)
            {
                result.AddRange(inputKeys);
                inputKeys.Clear();
            }
            return result;
        }
    }
}
